﻿using Aspose.Words.Lists;
using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.DAL;
using Ledict.ConditionExtract.Model;
using Ledict.Utility.Msg;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace Ledict.ConditionExtract.Frm.NodeTree
{
    /// <summary>
    /// 默认来源配置
    /// </summary>
    public partial class FrmSourceDefaultSetting : BaseForm
    {

        /// <summary>
        /// 父窗体选择树节点
        /// </summary>
        public TreeNode ClickNode { get; set; }

        //操作默认来源bll
        ExpressSourceDefaultSettingsBLL esd = new ExpressSourceDefaultSettingsBLL();

        //string nodeType = string.Empty;
        private int expressType = 0;
        public DataTable sysExpressSourceTable = new DataTable();
        NewIDBLL newid = new NewIDBLL();
        AboutRegexBLL regexbll = new AboutRegexBLL();
        Express_SourceBLL SourceBLL = new Express_SourceBLL();
        CaseCauseBLL casebll = new CaseCauseBLL();

        /// <summary>
        /// 构造函数 type 0:添加 1:选择
        /// 一键添加的逻辑为，按照节点类型进行默认配置，一键添加的时候按照每个节点配置类型的配置进行默认添加
        /// </summary>
        /// <param name="type"></param>
        public FrmSourceDefaultSetting(int type)
        {
            InitializeComponent();

            dgvExpressSelect.RowHeadersVisible = gdvExpressDefaultSource.RowHeadersVisible = false;
            dgvExpressSelect.AutoGenerateColumns = gdvExpressDefaultSource.AutoGenerateColumns = false;
            dgvExpressSelect.ColumnHeadersDefaultCellStyle.Alignment = gdvExpressDefaultSource.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //显示添加信息
            if (type == 0)
            {
                panelConfig.Visible = true;
                panelConfig.Dock = DockStyle.Fill;
                panelSelect.Visible = false;
            }
            else if (type == 1)//显示选择信息
            {
                panelSelect.Visible = true;
                panelSelect.Dock = DockStyle.Fill;
                panelConfig.Visible = false;
            }
            expressType = type;
        }

        /// <summary>
        /// 返回按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Yes;
        }

        /// <summary>
        /// 添加来源配置事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {

            if (ClickNode != null)
            {
                AddFrmSourceDefaultSetting frm = new AddFrmSourceDefaultSetting();
                //frm.CCNodeType = CCNodeType;
                //frm.CCNodeTypeName = CCNodeTypeName;
                //frm.CodeSubType = CCCodeSubType;
                //frm.CCCodeSubTypeName = CCCodeSubTypeName;
                frm.ClickNode = ClickNode;
                var dialogResult = frm.ShowDialog();
                if (dialogResult == DialogResult.Yes)
                {
                    //nodeType = CCCodeSubType == "0"|| CCCodeSubType ==null? CCNodeType : CCCodeSubType;
                    //if (nodeType.Contains("t"))
                    //{
                    //    level = 3;
                    //}
                    //else
                    //{
                    //    level = CCCodeSubType == "0" || CCCodeSubType == null ? 1 : 2;
                    //}
                    DataTable dt = esd.GetExpressSourceDefaultSettingsData(ClickNode.Tag.ToString());
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        dt.Columns.Add("publicInfoName");

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            if (!string.IsNullOrEmpty(dt.Rows[i]["PublicSourceID"].ToString()))
                            {
                                dt.Rows[i]["publicInfoName"] = dt.Rows[i]["PublicSourceID"].ToString() == "单一" ? "单一" : esd.ShowpublicInformation(dt.Rows[i]["PublicSourceID"].ToString(), dt.Rows[i]["DS_ID"].ToString());
                                //== "单一" ? "单一" : esd.ShowpublicInformation(dt.Rows[i]["PublicSourceID"].ToString(), dt.Rows[i]["DS_ID"].ToString());
                            }
                            else
                            {
                                dt.Rows[i]["publicInfoName"] = "单一";
                            }
                        }

                        gdvExpressDefaultSource.DataSource = dt;
                    }
                    frm.Close();
                    //frmDictEdit
                }
            }
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmSourceDefaultSetting_Load(object sender, EventArgs e)
        {

            sysExpressSourceTable.Columns.Add("ES_ID", typeof(string));
            sysExpressSourceTable.Columns.Add("CC_ID", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_ID", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_ParagraphID", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_Name", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_ParagraphName", typeof(string));
            sysExpressSourceTable.Columns.Add("CC_RegexInfoCode", typeof(string));
            sysExpressSourceTable.Columns.Add("ES_Purpose", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_TextType", typeof(string));
            sysExpressSourceTable.Columns.Add("EI_Name", typeof(string));
            sysExpressSourceTable.Columns.Add("ES_PurposeName", typeof(string));
            sysExpressSourceTable.Columns.Add("Source_TextTypeName", typeof(string));
            if (expressType == 0)
            {
                DataTable dt = esd.GetExpressSourceDefaultSettingsData(ClickNode.Tag.ToString());
                if (dt != null && dt.Rows.Count > 0)
                {
                    dt.Columns.Add("publicInfoName");

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (!string.IsNullOrEmpty(dt.Rows[i]["PublicSourceID"].ToString()) && dt.Rows[i]["PublicSourceID"].ToString() != "")
                        {
                            //获取逻辑，获取PublicSourceID共用的来源逻辑段等不包括本身
                            dt.Rows[i]["publicInfoName"] = dt.Rows[i]["PublicSourceID"].ToString() == "单一" ? "单一" : esd.ShowpublicInformation(dt.Rows[i]["PublicSourceID"].ToString(), dt.Rows[i]["DS_ID"].ToString());
                            //== "单一" ? "单一" : esd.ShowpublicInformation(dt.Rows[i]["PublicSourceID"].ToString(), dt.Rows[i]["DS_ID"].ToString());
                        }
                        else
                        {
                            dt.Rows[i]["publicInfoName"] = "单一";
                        }
                    }

                    gdvExpressDefaultSource.DataSource = dt;

                }
            }
            else if (expressType == 1)
            {
                DataTable dt = esd.GetExpressSourceDefaultSettingsData(ClickNode.Tag.ToString());
                if (dt != null && dt.Rows.Count > 0)
                {
                    dt.Columns.Add("publicInfoName");
                    dt.Columns.Add("Check");
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        dt.Rows[i]["Check"] = true;
                        if (!string.IsNullOrEmpty(dt.Rows[i]["PublicSourceID"].ToString()) && dt.Rows[i]["PublicSourceID"].ToString() != "")
                        {
                            dt.Rows[i]["publicInfoName"] = dt.Rows[i]["PublicSourceID"].ToString() == "单一" ? "单一" : esd.ShowpublicInformation(dt.Rows[i]["PublicSourceID"].ToString(), dt.Rows[i]["DS_ID"].ToString());
                            //== "单一" ? "单一" : esd.ShowpublicInformation(dt.Rows[i]["PublicSourceID"].ToString(), dt.Rows[i]["DS_ID"].ToString());
                        }
                        else
                        {
                            dt.Rows[i]["publicInfoName"] = "单一";
                        }
                    }

                    dgvExpressSelect.DataSource = dt;

                }
            }
        }

        /// <summary>
        /// 双击数据列表，删除数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gdvExpressDefaultSource_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

            if (e.RowIndex >= 0 && gdvExpressDefaultSource.Rows.Count >= 1 && !string.IsNullOrEmpty(gdvExpressDefaultSource.Rows[e.RowIndex].Cells["DS_ID"].Value.ToString()))
            {
                if (MsgBox.Ask("您确定要删除本条信息吗？") == DialogResult.Yes)
                {
                    if (!esd.DeleteExpressSourceDefaultSettingsDataByDsId(gdvExpressDefaultSource.Rows[e.RowIndex].Cells["DS_ID"].Value.ToString()))
                    {
                        MsgBox.Err("删除失败！");
                    }
                    else
                    {
                        gdvExpressDefaultSource.Rows.RemoveAt(e.RowIndex);
                    }
                }
            }
        }


        #region 设置进度条状态
        private void SleetT()
        {
            SetTextMessage(0);
        }

        private delegate void SetPos(int ipos);
        /// <summary>
        /// 设置进度条状态
        /// </summary>
        /// <param name="v1"></param>
        private void SetTextMessage(int v1)
        {
            if (v1 > 100)
            {
                v1 = 100;
            }
            if (this.InvokeRequired)
            {
                SetPos setpos = new SetPos(SetTextMessage);
                this.Invoke(setpos, new object[] { v1 });
            }
            else
            {
                this.progressBar2.Value = Convert.ToInt32(v1);
            }
        }
        #endregion

        /// <summary>
        /// 确定一键添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSure_Click(object sender, EventArgs e)
        {
            if (dgvExpressSelect.DataSource != null)
            {
                DataTable dt = (DataTable)dgvExpressSelect.DataSource;
                dt = dt.Select("Check='True'").CopyToDataTable();
                if (dt.Rows.Count == 0)
                {
                    MsgBox.Warn("请勾选需要配置的数据后再试");
                    return;
                }
                else
                {
                    ExpressSourceDefaultSettingsDAL dal = new ExpressSourceDefaultSettingsDAL();
                    Dictionary<int, ArrayList> nodeType = new Dictionary<int, ArrayList>();
                    CaseCauseBLL casecausebLL = new CaseCauseBLL();
                    Model.Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                    //获取节点下的节点
                    DataTable dtNodes = casecausebLL.GetCriminalNodes(ClickNode.Tag.ToString());
                    if (dtNodes != null && dtNodes.Rows.Count > 0)
                    {
                        //计算下面需要配置多少条
                        int count = 0;
                        DataTable dt1 = casecausebLL.GetDistinctCaseCauseNodeType(ClickNode.Tag.ToString());
                        List<int> nodes = new List<int>();
                        for (int i = 0; i < dt1.Rows.Count; i++)
                        {
                            if (!string.IsNullOrEmpty(dt1.Rows[i]["CC_NodeSubType"].ToString()) && dt1.Rows[i]["CC_NodeSubType"].ToString() != "0")
                            {
                                if (!nodes.Contains(Convert.ToInt32(dt1.Rows[i]["CC_NodeSubType"].ToString())))
                                {
                                    nodes.Add(Convert.ToInt32(dt1.Rows[i]["CC_NodeSubType"].ToString()));
                                    int k = dtNodes.Select("CC_NodeSubType=" + Convert.ToInt32(dt1.Rows[i]["CC_NodeSubType"].ToString())).Length;
                                    int k1 = dt.Select(" CC_NodeSubType= '" + dt1.Rows[i]["CC_NodeSubType"].ToString() + "'").Length;
                                    count += k * k1;
                                }
                            }
                            else if (!string.IsNullOrEmpty(dt1.Rows[i]["CC_NodeType"].ToString()))
                            {
                                if (!nodes.Contains(Convert.ToInt32(dt1.Rows[i]["CC_NodeType"].ToString())))
                                {
                                    nodes.Add(Convert.ToInt32(dt1.Rows[i]["CC_NodeType"].ToString()));
                                    int k = dtNodes.Select("CC_NodeType=" + Convert.ToInt32(dt1.Rows[i]["CC_NodeType"].ToString())).Length;
                                    int k1 = dt.Select(" CC_NodeType= '" + dt1.Rows[i]["CC_NodeType"].ToString() + "'").Length;
                                    count += k * k1;
                                }
                            }
                        }
                        progressBar2.Visible = true;
                        Thread thread = new Thread(new ThreadStart(SleetT));
                        thread.Start();
                        var iSuccess = 0;
                        var iFail = 0;
                        StringBuilder sbr = new StringBuilder();
                        sbr.Append("添加失败节点：");
                        ArrayList ar = new ArrayList();
                        for (int i = 0; i < dtNodes.Rows.Count; i++)
                        {
                            if (!string.IsNullOrEmpty(dtNodes.Rows[i]["CC_NodeSubType"].ToString()) && Convert.ToInt32(dtNodes.Rows[i]["CC_NodeSubType"].ToString()) > 0)
                            {
                                int nodeSubType = Convert.ToInt32(dtNodes.Rows[i]["CC_NodeSubType"].ToString());
                                ar.Clear();
                                if (!nodeType.ContainsKey(nodeSubType))
                                {
                                   
                                    if (dt.Select("CC_NodeSubType='" + nodeSubType + "'").Length > 0)
                                    {
                                        DataTable dt2 = dt.Select("CC_NodeSubType='" + nodeSubType + "'").CopyToDataTable();
                                        if (dt2 != null && dt2.Rows.Count > 0)
                                        {
                                            foreach (DataRow item in dt2.Rows)
                                            {
                                                SYS_Express_SourceDefaultSettings ses = dal.DataRowToModel(item);
                                                ar.Add(ses);
                                            }
                                        }
                                    }
                                    if (ar.Count > 0)
                                    {
                                        nodeType.Add(nodeSubType, DeepCopy<ArrayList>(ar));
                                    }
                                }
                                else if (nodeType.ContainsKey(nodeSubType))
                                {
                                    ar = DeepCopy<ArrayList>(nodeType[nodeSubType]);
                                }
                                if (ar.Count > 0)
                                {
                                    foreach (SYS_Express_SourceDefaultSettings ses in ar)
                                    {
                                        DataRow dr = sysExpressSourceTable.NewRow();
                                        dr["ES_ID"] = newid.JudgeDoc_CreateID("SYS_Express_Source");
                                        dr["CC_ID"] = dtNodes.Rows[i]["CC_ID"].ToString();
                                        dr["Source_ID"] = ses.CD_Code;
                                        dr["Source_ParagraphID"] = ses.CDL_Code;
                                        dr["Source_Name"] = ses.CD_Name;
                                        dr["Source_ParagraphName"] = ses.CDL_Name;
                                        if (ses.PublicSourceID == "单一" || ses.PublicSourceID == "")
                                        {
                                            nodeChild = new Model.Reg_InfoUnit();
                                            nodeChild.EI_Name = dtNodes.Rows[i]["CC_Name"].ToString();
                                            nodeChild.EN_ID = "EI_ID1507221438500001";
                                            nodeChild.EI_Remark = "";
                                            nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                            nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                            regexbll.AddReg_InfoUnit(nodeChild);
                                            dr["CC_RegexInfoCode"] = nodeChild.EI_Code;
                                        }
                                        else
                                        {
                                            if (dt.Select(" DS_ID='" + ses.PublicSourceID + "'").Length > 0)
                                            {
                                                SYS_Express_SourceDefaultSettings sess = dal.DataRowToModel(dt.Select(" DS_ID='" + ses.PublicSourceID + "'")[0]);
                                                //获取当前节点的来源，逻辑段等信息
                                                DataTable dt3 = SourceBLL.GetExpressSourceDt(dr["CC_ID"].ToString(), sess.CD_Code, sess.CDL_Code, sess.ES_PurposeID, sess.TextType_Code);
                                                if (dt3 != null && dt3.Rows.Count > 0)
                                                {
                                                    if (!string.IsNullOrEmpty(dt3.Rows[0]["CC_RegexInfoCode"].ToString()))
                                                    {
                                                        dr["CC_RegexInfoCode"] = dt3.Rows[0]["CC_RegexInfoCode"].ToString();
                                                    }
                                                }
                                                else
                                                {
                                                    nodeChild = new Model.Reg_InfoUnit();
                                                    nodeChild.EI_Name = dtNodes.Rows[i]["CC_Name"].ToString();
                                                    nodeChild.EN_ID = "EI_ID1507221438500001";
                                                    nodeChild.EI_Remark = "";
                                                    nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                                    nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                                    regexbll.AddReg_InfoUnit(nodeChild);
                                                    SysExpressSource model1 = new SysExpressSource
                                                    {
                                                        ES_ID = newid.JudgeDoc_CreateID("SYS_Express_Source"),
                                                        CC_ID = dtNodes.Rows[i]["CC_ID"].ToString(),
                                                        Source_ID = sess.CD_Code,
                                                        Source_Name = sess.CD_Name,
                                                        Source_ParagraphID = sess.CDL_Code,
                                                        Source_ParagraphName = sess.CDL_Name,
                                                        EsPurposeId = sess.ES_PurposeID,
                                                        Source_TextType = sess.TextType_Code,
                                                        EsPurposeName = sess.ES_PurposeName,
                                                        CC_RegexInfoCode = nodeChild.EI_Code,
                                                    };

                                                    if (!SourceBLL.Exists(model1.CC_ID, model1.Source_ID, model1.Source_ParagraphID, model1.Source_TextType, model1.EsPurposeId))
                                                    {
                                                        if (SourceBLL.AddSource(model1))
                                                        {
                                                            iSuccess++;
                                                            SetTextMessage(100 * iSuccess / count);
                                                        }
                                                        else
                                                        {
                                                            sbr.Append(model1.CC_ID + "(" + dtNodes.Rows[i]["CC_Name"].ToString() + "),");
                                                            iFail++;
                                                        }
                                                    }
                                                    dr["CC_RegexInfoCode"] = nodeChild.EI_Code;
                                                }
                                            }
                                            else
                                            {
                                                nodeChild = new Model.Reg_InfoUnit();
                                                nodeChild.EI_Name = dtNodes.Rows[i]["CC_Name"].ToString();
                                                nodeChild.EN_ID = "EI_ID1507221438500001";
                                                nodeChild.EI_Remark = "";
                                                nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                                nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                                regexbll.AddReg_InfoUnit(nodeChild);
                                                dr["CC_RegexInfoCode"] = nodeChild.EI_Code;
                                            }
                                        }
                                        dr["ES_Purpose"] = ses.ES_PurposeID;
                                        dr["Source_TextType"] = ses.TextType_Code;
                                        SysExpressSource model = new SysExpressSource
                                        {
                                            ES_ID = dr["ES_ID"].ToString(),
                                            CC_ID = dr["CC_ID"].ToString(),
                                            Source_ID = dr["Source_ID"].ToString(),
                                            Source_Name = dr["Source_Name"].ToString(),
                                            Source_ParagraphID = dr["Source_ParagraphID"].ToString(),
                                            Source_ParagraphName = dr["Source_ParagraphName"].ToString(),
                                            EsPurposeId = dr["ES_Purpose"].ToString(),
                                            Source_TextType = dr["Source_TextType"].ToString(),
                                            EsPurposeName = ses.ES_PurposeName,
                                            CC_RegexInfoCode = dr["CC_RegexInfoCode"].ToString(),
                                        };
                                        if (!SourceBLL.Exists(model.CC_ID, model.Source_ID, model.Source_ParagraphID, model.Source_TextType, model.EsPurposeId))
                                        {
                                            if (SourceBLL.AddSource(model))
                                            {
                                                iSuccess++;
                                                SetTextMessage(100 * iSuccess / count);
                                            }
                                            else
                                            {
                                                sbr.Append(model.CC_ID + "(" + dtNodes.Rows[i]["CC_Name"].ToString() + "),");
                                                iFail++;
                                            }
                                        }
                                    }
                                }
                            }
                            else if (!string.IsNullOrEmpty(dtNodes.Rows[i]["CC_NodeType"].ToString()) && Convert.ToInt32(dtNodes.Rows[i]["CC_NodeType"].ToString()) > 0)
                            {
                                int ccNodeType = Convert.ToInt32(dtNodes.Rows[i]["CC_NodeType"].ToString());
                                ar.Clear();
                                if (!nodeType.ContainsKey(ccNodeType))
                                {

                                    if (dt.Select("CC_NodeType='" + ccNodeType + "'").Length > 0)
                                    {
                                        DataTable dt2 = dt.Select("CC_NodeType='" + ccNodeType + "'").CopyToDataTable();
                                        if (dt2 != null && dt2.Rows.Count > 0)
                                        {
                                            foreach (DataRow item in dt2.Rows)
                                            {
                                                SYS_Express_SourceDefaultSettings ses = dal.DataRowToModel(item);
                                                ar.Add(ses);
                                            }
                                        }
                                    }
                                    if (ar.Count > 0)
                                    {
                                        nodeType.Add(ccNodeType, DeepCopy<ArrayList>(ar));
                                    }
                                }
                                else if (nodeType.ContainsKey(ccNodeType))
                                {
                                    ar = DeepCopy<ArrayList>(nodeType[ccNodeType]);
                                }
                                if (ar.Count > 0)
                                {
                                    //裁判理由根据裁判结果去判断
                                    if (ccNodeType == 17)
                                    {
                                        int num = casebll.GetNextNodeType(dtNodes.Rows[i]["CC_ID"].ToString());
                                        if (num == 0)
                                        {
                                            if (!nodeType.ContainsKey(-1))
                                            {
                                                ArrayList arYuan = new ArrayList();
                                                //原告
                                                foreach (SYS_Express_SourceDefaultSettings ses in ar)
                                                {
                                                    if (ses.CDL_Name.Contains("裁判理由") || ses.CDL_Name.Contains("原告"))
                                                    {
                                                        arYuan.Add(ses);
                                                    }
                                                }
                                                if (arYuan.Count > 0)
                                                {
                                                    nodeType.Add(-1, DeepCopy<ArrayList>(arYuan));
                                                    ar = arYuan;
                                                }

                                            }
                                            else if (nodeType.ContainsKey(-1))
                                            {
                                                ar = DeepCopy<ArrayList>(nodeType[-1]);
                                            }
                                        }
                                        else if (num == 1)
                                        {
                                            if (!nodeType.ContainsKey(-2))
                                            {
                                                //被告
                                                ArrayList arYuan = new ArrayList();
                                                //原告
                                                foreach (SYS_Express_SourceDefaultSettings ses in ar)
                                                {
                                                    if (ses.CDL_Name.Contains("裁判理由") || ses.CDL_Name.Contains("被告"))
                                                    {
                                                        arYuan.Add(ses);
                                                    }
                                                }
                                                if (arYuan.Count > 0)
                                                {
                                                    nodeType.Add(-2, DeepCopy<ArrayList>(arYuan));
                                                    ar = arYuan;
                                                }
                                            }
                                            else if (nodeType.ContainsKey(-2))
                                            {
                                                ar = DeepCopy<ArrayList>(nodeType[-2]);
                                            }
                                        }
                                    }
                                    foreach (SYS_Express_SourceDefaultSettings ses in ar)
                                    {
                                        DataRow dr = sysExpressSourceTable.NewRow();
                                        dr["ES_ID"] = newid.JudgeDoc_CreateID("SYS_Express_Source");
                                        dr["CC_ID"] = dtNodes.Rows[i]["CC_ID"].ToString();
                                        dr["Source_ID"] = ses.CD_Code;
                                        dr["Source_ParagraphID"] = ses.CDL_Code;
                                        dr["Source_Name"] = ses.CD_Name;
                                        dr["Source_ParagraphName"] = ses.CDL_Name;
                                        if (ses.PublicSourceID == "单一" || ses.PublicSourceID == "")
                                        {
                                            nodeChild = new Model.Reg_InfoUnit();
                                            nodeChild.EI_Name = dtNodes.Rows[i]["CC_Name"].ToString();
                                            nodeChild.EN_ID = "EI_ID1507221438500001";
                                            nodeChild.EI_Remark = "";
                                            nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                            nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                            regexbll.AddReg_InfoUnit(nodeChild);
                                            dr["CC_RegexInfoCode"] = nodeChild.EI_Code;
                                        }
                                        else
                                        {
                                            if (dt.Select(" DS_ID='" + ses.PublicSourceID + "'").Length > 0)
                                            {
                                                SYS_Express_SourceDefaultSettings sess = dal.DataRowToModel(dt.Select(" DS_ID='" + ses.PublicSourceID + "'")[0]);
                                                DataTable dt3 = SourceBLL.GetExpressSourceDt(dr["CC_ID"].ToString(), sess.CD_Code, sess.CDL_Code, sess.ES_PurposeID, sess.TextType_Code);
                                                if (dt3 != null && dt3.Rows.Count > 0)
                                                {
                                                    if (!string.IsNullOrEmpty(dt3.Rows[0]["CC_RegexInfoCode"].ToString()))
                                                    {
                                                        dr["CC_RegexInfoCode"] = dt3.Rows[0]["CC_RegexInfoCode"].ToString();
                                                    }
                                                }
                                                else
                                                {
                                                    nodeChild = new Model.Reg_InfoUnit();
                                                    nodeChild.EI_Name = dtNodes.Rows[i]["CC_Name"].ToString();
                                                    nodeChild.EN_ID = "EI_ID1507221438500001";
                                                    nodeChild.EI_Remark = "";
                                                    nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                                    nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                                    regexbll.AddReg_InfoUnit(nodeChild);
                                                    SysExpressSource model1 = new SysExpressSource
                                                    {
                                                        ES_ID = newid.JudgeDoc_CreateID("SYS_Express_Source"),
                                                        CC_ID = dtNodes.Rows[i]["CC_ID"].ToString(),
                                                        Source_ID = sess.CD_Code,
                                                        Source_Name = sess.CD_Name,
                                                        Source_ParagraphID = sess.CDL_Code,
                                                        Source_ParagraphName = sess.CDL_Name,
                                                        EsPurposeId = sess.ES_PurposeID,
                                                        Source_TextType = sess.TextType_Code,
                                                        EsPurposeName = sess.ES_PurposeName,
                                                        CC_RegexInfoCode = nodeChild.EI_Code,
                                                    };

                                                    if (!SourceBLL.Exists(model1.CC_ID, model1.Source_ID, model1.Source_ParagraphID, model1.Source_TextType, model1.EsPurposeId))
                                                    {
                                                        if (SourceBLL.AddSource(model1))
                                                        {
                                                            iSuccess++;
                                                            SetTextMessage(100 * iSuccess / count);
                                                        }
                                                        else
                                                        {
                                                            sbr.Append(model1.CC_ID + "(" + dtNodes.Rows[i]["CC_Name"].ToString() + "),");
                                                            iFail++;
                                                        }
                                                    }
                                                    dr["CC_RegexInfoCode"] = nodeChild.EI_Code;
                                                }
                                            }
                                            else
                                            {
                                                nodeChild = new Model.Reg_InfoUnit();
                                                nodeChild.EI_Name = dtNodes.Rows[i]["CC_Name"].ToString();
                                                nodeChild.EN_ID = "EI_ID1507221438500001";
                                                nodeChild.EI_Remark = "";
                                                nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                                nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                                regexbll.AddReg_InfoUnit(nodeChild);
                                                dr["CC_RegexInfoCode"] = nodeChild.EI_Code;
                                            }
                                        }
                                        dr["ES_Purpose"] = ses.ES_PurposeID;
                                        dr["Source_TextType"] = ses.TextType_Code;
                                        SysExpressSource model = new SysExpressSource
                                        {
                                            ES_ID = dr["ES_ID"].ToString(),
                                            CC_ID = dr["CC_ID"].ToString(),
                                            Source_ID = dr["Source_ID"].ToString(),
                                            Source_Name = dr["Source_Name"].ToString(),
                                            Source_ParagraphID = dr["Source_ParagraphID"].ToString(),
                                            Source_ParagraphName = dr["Source_ParagraphName"].ToString(),
                                            EsPurposeId = dr["ES_Purpose"].ToString(),
                                            Source_TextType = dr["Source_TextType"].ToString(),
                                            EsPurposeName = ses.ES_PurposeName,
                                            CC_RegexInfoCode = dr["CC_RegexInfoCode"].ToString(),
                                        };
                                        if (!SourceBLL.Exists(model.CC_ID, model.Source_ID, model.Source_ParagraphID, model.Source_TextType, model.EsPurposeId))
                                        {
                                            if (SourceBLL.AddSource(model))
                                            {
                                                iSuccess++;
                                                SetTextMessage(100 * iSuccess / count);
                                            }
                                            else
                                            {
                                                sbr.Append(model.CC_ID + "(" + dtNodes.Rows[i]["CC_Name"].ToString() + "),");
                                                iFail++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        SetTextMessage(100);
                        progressBar2.Visible = false;
                        MsgBox.OK(string.Format("添加成功{0}条。\r\n失败{1}条。{2}", iSuccess, iFail, sbr.ToString()));

                        thread.Abort();
                        this.Close();
                    }
                }
            }

        }

        /// <summary>
        /// 对象深度拷贝
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T DeepCopy<T>(T obj)
        {
            object retval;
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
                bf.Serialize(ms, obj);
                ms.Position = 0;
                retval = bf.Deserialize(ms);
                ms.Close();
            }
            return (T)retval;
        }
        private void dgvExpressSelect_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //if (e.RowIndex >= 0 && gdvExpressDefaultSource.Rows.Count > 1 && !string.IsNullOrEmpty(gdvExpressDefaultSource.Rows[e.RowIndex].Cells["DS_ID"].Value.ToString()))
            //{
            //    if (MsgBox.Ask("您确定要删除本条信息吗？") == DialogResult.Yes)
            //    {
            //        if (!esd.DeleteExpressSourceDefaultSettingsDataByDsId(gdvExpressDefaultSource.Rows[e.RowIndex].Cells["DS_ID"].Value.ToString()))
            //        {
            //            MsgBox.Err("删除失败！");
            //        }
            //        else
            //        {
            //            gdvExpressDefaultSource.Rows.RemoveAt(e.RowIndex);
            //        }
            //    }
            //}

        }
    }
}
